package com.atguigu.reggie.controller;


import com.atguigu.reggie.common.BaseContext;
import com.atguigu.reggie.common.R;
import com.atguigu.reggie.dto.DishDto;
import com.atguigu.reggie.entity.Category;
import com.atguigu.reggie.entity.Dish;
import com.atguigu.reggie.entity.DishFlavor;
import com.atguigu.reggie.entity.Setmeal;
import com.atguigu.reggie.service.CategoryService;
import com.atguigu.reggie.service.DishFlavorService;
import com.atguigu.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-13 12:55
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据page和pageSize返回对应菜品页面
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        // 日志输出
        log.info("page={},pageSize={}",page,pageSize);

        // 创建分类构造器page对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        // 创建dishLambdaQueryWrapper对象
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();

        // 添加eq条件和根据最近更新时间排序
        dishLambdaQueryWrapper.like(StringUtils.hasLength(name),Dish::getName,name).orderByDesc(Dish::getUpdateTime);

        // 进行分页查询
        dishService.page(dishPage,dishLambdaQueryWrapper);

        // 进行对象拷贝,并忽略掉records对象
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        // 获取dishPage中的records对象
        List<Dish> dishPageRecords = dishPage.getRecords();

        // 通过stream流的方式将records集合中的所有dish对象转为dishDto对象
        List<DishDto> dishDtoPageRecords = dishPageRecords.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            //将item中的值拷贝到dishDto中
            BeanUtils.copyProperties(item,dishDto);

            // 获取每一个dish对象的分类id
            Long categoryId = item.getCategoryId();

            // 根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            // 将查询到的categoryName赋值给dishDto
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            // 返回dishDto对象
            return dishDto;
        }).collect(Collectors.toList());

        // 将更新后的records赋值给dishDtoPage
        dishDtoPage.setRecords(dishDtoPageRecords);

        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        // 日志输出
        log.info(dishDto.toString());

        // 新增菜品，同时插入菜品对应的口味数据，需要操作两张表，dish,dish_flavor
        dishService.saveWithFlavor(dishDto);

        // 精确清理
/*        String key = "dish_" + dishDto.getCategoryId() + "_" + "1";
        redisTemplate.delete(key);*/

        return R.success("新增菜品成功");
    }

    /**
     * 批量修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> status(@PathVariable("status") int status,@RequestParam("ids") List<Long> ids){
        // 创建修改构造器
        // UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        // 查询此次修改状态的Dish
        List<Dish> dishes = dishService.listByIds(ids);

        // 添加条件
        dishLambdaUpdateWrapper.in(Dish::getId,ids).set(Dish::getStatus,status);
        dishLambdaUpdateWrapper.set(Dish::getUpdateTime, LocalDateTime.now()).set(Dish::getUpdateUser, BaseContext.getCurrentId());

        // 执行修改
        dishService.update(dishLambdaUpdateWrapper);

        // 精确清理
/*        for (Dish dish : dishes) {
            String key = "dish_" + dish.getCategoryId() + "_" + "1";
            redisTemplate.delete(key);
        }*/

        return R.success("操作成功");
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        // 通过id查询dishDto信息
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);

    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        // 日志输出
        log.info(dishDto.toString());

        // 进行更新
        dishService.updateWithFlavor(dishDto);

        // 精确清理
/*        String key = "dish_" + dishDto.getCategoryId() + "_" + "1";
        redisTemplate.delete(key);*/

        // 返回修改成功信息
        return R.success("修改成功");
    }

    /**
     * 删除菜品 / 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
        // 调用对应的remove方法
        dishService.removeWithFlavorByIds(ids);

        return R.success("套餐数据删除成功");

    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId +'_'+ #dish.status")
    public R<List<DishDto>> list(Dish dish){
        // 创建一个dishDtoList对象
        List<DishDto> dishDtoList = null;

        // 动态构造key，先构造一个key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus(); // dish_1234564879_1

        // 先从redis中获取缓存数据
      /*  dishDtoList  = (List<DishDto>)redisTemplate.opsForValue().get(key);

        if (dishDtoList != null){
            // 如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);

        }*/

        // 创建查询条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId,dish.getCategoryId());

        // 只查在售的
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);

        // 添加排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        // 调用list方法查询
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);

        // 改造dish为dishDto
        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            // 拷贝dish属性到dishDto
            BeanUtils.copyProperties(item,dishDto);

            // 查询构造器
            LambdaQueryWrapper<DishFlavor> dishDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishDtoLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());

            // 查询dishFlavorList
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishDtoLambdaQueryWrapper);

            // 返回改造结果
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

       /* // 如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis, 设置缓存时间为60分钟
        redisTemplate.opsForValue().set(key,dishDtoList,60,TimeUnit.MINUTES);
        log.info("key={}",redisTemplate.opsForValue().get(key));*/

        // 返回结果
        return R.success(dishDtoList);
    }

}
